<template>
	<view class="coupon" :style="{ '--color': vuex_config.themeColor1 }">
		<template v-if="dataListParams.init">
			<u-tabs-swiper ref="tabs" :list="list" :is-scroll="false" :current="current" active-color=" #00A6F8"
				@change="change"></u-tabs-swiper>
			<view class="coupon-box" v-for="(item, index) in dataList" :key="index">
				<view class="coupon_left">
					<image v-if="current !== 1" class="box-img" src="../static/coum.png"></image>
					<image v-else class="box-img" src="../static/coum1.png"></image>

					<view class="box-price">
						<view class="price-num">
							<text class="price-icon">￥</text>
							<text class="price-num">{{ item.price || 0 }}</text>
						</view>
						<view class="price-title">满{{ item.full_reduce || 0 }}元可用</view>
					</view>
				</view>
				<view class="coupon-tip" v-if="current !== 1 && item.nearly ? true : false"
					:style="{ 'background-color': item.nearly === 1 ? vuex_config.themeColor1 : '#ccc' }">
					{{ item.nearly == 1 ? '即将过期' : '已过期' }}
				</view>
				<view class="box-right">
					<view class="box-right-title u-line-1">{{ item.name }}</view>
					<view class="box-right-subtitle u-line-2">{{ item.remark || '' }}</view>
					<view class="box-right-btn">
						<view class="title" v-if="current !== 1">
							到期：{{ (current == 2 ? item.end_effective : item.coupon_receive_effective) | format }}</view>
						<view class="title" v-else>使用： {{ item.coupon_receive_use | format }}</view>
					</view>
					<view class="btn-box">
						<!-- 						<view  v-if="current == 0 " @click="changeCoupon(item, index)">
							
						</view> -->
						<button class="btn zhuan" v-if="current == 0 " :id="item.coupon_receive_id + ',' + item.pk_id"  open-type="share">转赠</button>
						<view class="btn ling" v-if="current !== 1 && item.nearly !== 2"
							@click="changeCoupon(item, index)">
							{{ current === 0 ? '去使用' : '领取' }}
						</view>
					</view>
				</view>
			</view>
			<sww-load-more :params="dataListParams" @load="loadMore"></sww-load-more>
		</template>
		<sww-login></sww-login>
		<u-popup v-model="show" mode="center" length="60%">
			<view class="pop-box">
				<view class="">线下核销</view>
				<view class="content">
					<view class="img-box">
						<image class="box-img" :src="qrCodeUrl" mode=""></image>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		pagingMixin
	} from '@/mixins/pagingMixin.js';
	import {
		formatDate,
		getDiff,
		timeStamp
	} from '@/utils/moment/index.js';
	import {
		resGet
	} from '@/common/http.request.js';
	import {
		pageShare
	} from '@/mixins/pageShare';
	export default {
		mixins: [pagingMixin, pageShare],
		data() {
			return {
				// ,{name:'已过期'}
				list: [{
						name: '未使用',
						state: 3
					},
					{
						name: '已使用',
						state: 4
					},
					{
						name: '待领取',
						state: 1
					}
				],
				current: 2,
				newUser: false, //判断是否是新用户
				show: false,
				qrCodeUrl: '',
			};
		},
		filters: {
			format(data) {
				return formatDate(data, 'YYYY-MM-DD hh:mm');
			}
		},
		onLoad(options) {
			if(options && options.current){
				this.current = Number(options.current)
			}
			this.$login('initPage', null, 'goBack').then(() => {
				this.initPage();
			});
		},
		onShareAppMessage: function(res) {
			if (res.from == 'button') {
				// 小程序点击分享按钮转赠
				return this.giveShare(res.target.id);
			} else {
				this.shareParams = {
					title: '',
					desc: '',
					path: '',
					imgUrl: ''
				};
				return this.getShareAppMessage();
			}
		},
		onShareTimeline: function() {
			return this.getShareTimeline();
		},
		onReachBottom: function() {
			this.loadMore();
		},
		methods: {
			goBack() {
				this.uniBack();
			},
			// 赠送分享
			giveShare(id) {
				return new Promise((resolve, reject) => {
					this.$loading();
					let ids = id.split(',')
					this.$resPost('GetCouponInfo', {
						pk_id:ids[1],
						users_id:this.vuex_user.pk_id
					})
						.then(({ data }) => {
							// 调用转发赠送接口
							this.shareParams = {
								title: data.name || '恭喜发财，大吉大利',
								path: `package/user/coupon/receiveCoupon`,
								query: { id: data.pk_id,user_id:this.vuex_user.pk_id,coupon_receive_id:ids[0]},
								imgUrl: data.img
							};
							resolve(this.getShareAppMessage());
							this.$hide();
						})
						.catch(() => {
							this.shareParams = {
								title: '',
								desc: '',
								path: '',
								imgUrl: ''
							};
							resolve();
						});
				});
			},
			// 页面初次渲染
			initPage() {
				this._init_data(
					'GetCouponList', {
						type: this.list[this.current].state
					}, {
						callBack: this.filterList
					}
				);

				// 判断是否是新用户
				if (new Date().getTime() <= Number(timeStamp(this.vuex_user.date_creation)) + 86400000) {
					this.newUser = true;
				}
			},
			// 判断未使用时是否将近过期
			filterList(list) {
				if (this.current === 1) {
					return list;
				} else if (this.current == 0) {
					return list.map(item => {
						let end = new Date(item.coupon_receive_effective);
						let start = new Date();
						if (end.getTime() <= start.getTime()) {
							item.nearly = 2; // 1.即将过期  2已过期
						} else {
							let day = getDiff(start, end);
							item.nearly = day > 1 ? 0 : 1;
						}
						return item;
					});
				} else if (this.current == 2) {
					return list.map(item => {
						let end = new Date(item.end_effective);
						let start = new Date();
						if (end.getTime() <= start.getTime()) {
							item.nearly = 2; // 1.即将过期  2已过期
						} else {
							let day = getDiff(start, end);
							item.nearly = day > 1 ? 0 : 1;
						}
						return item;
					});
				}
			},
			loadMore() {
				this._load_data();
			},
			change(index) {
				this.current = index;
				this.initPage();
			},
			// 使用、领取优惠券
			changeCoupon(item, index) {
				if (this.current == 2) {
					if (item.is_give == 1 && !this.newUser) {
						this.$toast('没有领取权限');
						return;
					}
					if (item.count <= 0) {
						this.$toast('已领取完');
						return;
					}
					this.receive(item, index);
				} else {
					if (item.fk_class_id == '5') {// 餐饮核销优惠券
						this.show = true
						let url =
							`/package/restaurant/OfflinePlay/chooseOfflineplay?userId=${this.vuex_user.pk_id}&coupon_id=${item.pk_id}`
						this.getcode(url)
					}else if(item.fk_class_id == 6){// 供应商优惠券
						this.$linkTo(
							`/package/index/shopDetail/index?id=${item.fk_pro_id}`
						);
					} else if (item.fk_pro_id && item.fk_class_id > 0 && item.fk_class_id != 99) {
						let obj = {
							1: 1,
							2: 9,
							3: 3,
							4: 4,
						}
						let arr = item.fk_pro_id.split(',');
						arr.length == 1 ?
							this.$toProd({
								prodType: obj[item.fk_class_id],
								pk_id: item.fk_pro_id
							}) :
							this.$linkTo(
								`/package/product/prodSearch/couponproductSearch?id=${item.fk_pro_id}&type=${item.fk_class_id}`
							);
					} else {
						// this.$linkTo('index');
						this.$linkTo('/package/user/coupon-code/index?urdata=' + encodeURIComponent(JSON.stringify(item)))
					}
				}
			},
			//生成二维码
			getcode(url) {
				let that = this
				resGet('GenerateQRCode', {
					business_id: '',
					users_id: '',
					content: encodeURIComponent(url)
				}, {}, {
					blob: true
				}).then(res => {
					// #ifdef MP-BAIDU
					uni.loading()
					// 傻逼百度小程序不支持 uni.arrayBufferToBase64 并且本身也没有arrayBuffer转base64的api  所以需要写入文件后转换成url显示
					const fsm = swan.getFileSystemManager();
					const FILE_BASE_NAME = new Date().getTime();
					const filePath = swan.env.USER_DATA_PATH + '/' + FILE_BASE_NAME + '.png'
					fsm.writeFile({
						filePath,
						data: res,
						success() {
							that.qrCodeUrl = filePath
							uni.hideLoading()
						},
						fail() {
							uni.hideLoading()
							this.$toast('生成失败，请重新刷新')
						}
					})
					// #endif 

					// #ifndef  MP-ALIPAY ||  MP-BAIDU	
					this.qrCodeUrl = 'data:image/jpeg;base64,' + uni.arrayBufferToBase64(res || []);
					// #endif 

					// #ifdef  MP-ALIPAY	
					this.qrCodeUrl = 'data:image/jpeg;base64,' + my.arrayBufferToBase64(res || [])
					// #endif 
					this.$hide();
				})
			},
			// 优惠券领取
			receive(item, index) {
				this.$loading();
				let day = item.effective || 1;
				let date = new Date();
				date.setDate(date.getDate() + day);
				date = formatDate(date, 'YYYY-MM-DD HH:mm:ss');
				this.$resPost('AddCouponReceive', {
					coupon_id: item.pk_id,
					date_effective: date
				}).then(() => {
					this.$toast('领取成功');
					setTimeout(() => {
						this.$hide();
					}, 800);
					this.dataList.splice(index, 1);
				});
			}
		}
	};
</script>
<style>
	page {
		background-color: #f5f5f5;
	}
</style>
<style lang="scss" scoped>
	.coupon {
		.coupon-box {
			display: flex;
			align-items: center;
			margin: 20rpx 30rpx;
			background-color: #fff;
			position: relative;
			overflow: hidden;

			.coupon_left {
				height: 220rpx;
				width: 252rpx;
				position: relative;

				.box-price {
					position: absolute;
					top: 0;
					left: 0;
					width: 100%;
					height: 100%;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;

					.price-num {
						display: flex;
						align-items: flex-end;

						.price-icon {
							color: #fff;
							font-size: 32rpx;
							position: relative;
							bottom: 11rpx;
						}

						.price-num {
							font-size: 60rpx;
							color: #fff;
						}
					}

					.price-title {
						color: #fff;
						font-size: 24rpx;
					}
				}
			}

			.coupon-tip {
				width: 170rpx;
				line-height: 40rpx;
				color: #fff;
				position: absolute;
				right: -40rpx;
				top: 24rpx;
				font-size: 20rpx;
				text-align: center;
				transform: rotate(45deg);
			}

			.box-right {
				flex: 1;
				overflow: hidden;
				padding: 16rpx 30rpx;

				.box-right-title {
					font-size: 30rpx;
					color: #333;
					font-weight: bold;
				}

				.box-right-subtitle {
					font-size: 24rpx;
					line-height: 34rpx;
					min-height: 34rpx;
					color: #999;
					margin: 10rpx 10rpx 0 0;
					padding-bottom: 4rpx;
					border-bottom: 1px dashed #dddddd;
					font-weight: bold;
				}

				.box-right-btn {
					display: flex;
					align-items: center;
					padding-top: 18rpx;

					.title {
						flex: 1;
						overflow: hidden;
						font-size: 22rpx;
						color: #c9c9c9;
					}


				}
			}
		}

		.btn-box {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			padding-top: 20rpx;

			.btn {
				margin-right: -10rpx;
				display: inline-block;
				font-size: 24rpx;
				border-radius: 30rpx;
				padding: 6rpx 20rpx;

				&.ling {
					color: var(--color);
					border: 1px solid var(--color);
				}

				&.zhuan {
					line-height: 32rpx;
					background-color: #fff;
					color: #e5a75a;
					border: 1px solid #e5a75a;
					margin-right: 20rpx;
				}
			}
		}

		.pop-box {
			padding: 20rpx;
			display: flex;
			flex-direction: column;

			.content {
				margin-top: 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				.img-box {
					padding: 10rpx;
					border: 1px solid #f1f1f1;

					.box-img {
						width: 300rpx;
						height: 300rpx;
					}
				}
			}
		}
	}
</style>
